package com.appwx.sdk.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import android.text.TextUtils;

public class FileUtil {
	public static final String PHOTO_CACHE_DIR = "/sdcard/ICER/.cache/";

	public static InputStream getRequest(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		if (conn.getResponseCode() == 200) {
			return conn.getInputStream();
		}
		return null;
	}

	public static boolean isUrlPicExist(String dir, String url, String size) {
		String path = getLocPathFromUrl(PHOTO_CACHE_DIR, url, size);
		File file = new File(path);
		return file.exists();
	}

	public static String getLocPathFromUrl(String dir, String url, String size) {
		String path = dir + MD5Encrypt(url).replaceAll("/", "_") + size;
		return path;
	}
	
	public static boolean isFileExist(String filePath){
		if (TextUtils.isEmpty(filePath)) {
			return false;
		}
		File tempFile = new File(filePath);
		return tempFile.exists();
	}
	public static String saveImgFromUrl(String imgUrl, String size) {
		String filePath = "";
		File dir = new File(PHOTO_CACHE_DIR);
		if(!dir.exists()){
			dir.mkdirs();
		}
		try {
			filePath = getLocPathFromUrl(PHOTO_CACHE_DIR, imgUrl, size);
			// 存放地址
			File img = new File(filePath);
			// 生成图片
			if(img.exists()){
				return filePath;
			}
			BufferedInputStream in = new BufferedInputStream(
					new URL(imgUrl+size).openStream());
			BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(img));
			byte[] buf = new byte[2048];
			int length = in.read(buf);
			while (length != -1) {
				out.write(buf, 0, length);
				length = in.read(buf);
			}
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return filePath;
	}

	public static String MD5Encrypt(String encryptText) {
		byte[] HAMC = null;
		encryptText = encryptText + "&icerdev123";
		try {
			Mac mac = Mac.getInstance("HmacMD5");
			SecretKeySpec spec = new SecretKeySpec("icerdev123".getBytes(),
					"HmacMD5");
			mac.init(spec);
			HAMC = mac.doFinal(encryptText.getBytes("US-ASCII"));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return BASE64Encoder.encode(HAMC);
	}
}
